import React, { Component } from 'react'
import { Button, Icon, Input, message, Popconfirm, Table } from 'antd'
import '../../less/index.less'
import '../../less/program-list.less'
import '../../less/common.less'
import EditableCell from '../common/editable-cell'
import ShowToStudentCell from './show-student-cell'
import ReactDragListView from 'react-drag-listview'
import * as topicActions from '../../actions/topic'
import { connect } from 'react-redux'
import Task from './task-box'
import TaskOperation from './task-operation'
import { convertContent } from '../../constant/lang-util'

class Topic extends Component {
  constructor (props) {
    super(props)
    this.state = {
      deleteTopicName: '',
      expandIconAsCell: true,
      expandRowByClick: false,
      operationEnable: false,
      sourceTaskIds: []
    }
  }

  componentWillMount () {
    this.props.getProgramsAndSubTopics()
  }

  onDelete (record) {
    this.state.deleteTopicName.trim() === record.title.trim()
      ? this.props.deleteTopic(this.props.programId, record.id) : message.info(convertContent('请输入正确的主题名称'))
  }

  handleAdd () {
    const newTopic = {
      title: '',
      programId: this.props.programId
    }
    this.props.addTopic(this.props.programId, newTopic)
  }

  onCellChange (topicId) {
    return (value) => {
      this.props.updateTopic(this.props.programId, topicId, value.trim())
    }
  }

  getInputValue (e) {
    this.setState({deleteTopicName: e.target.value})
  }

  selectTasks (selectTaskIds, selected) {
    let sourceTaskIds = this.state.sourceTaskIds
    if (selected) {
      selectTaskIds.forEach(taskId => sourceTaskIds.push(taskId))
    } else {
      sourceTaskIds = sourceTaskIds.filter(taskId => !selectTaskIds.includes(taskId))
    }
    this.setState({sourceTaskIds})
  }

  expandedRowRender (record) {
    const {readOnly, id} = this.props.program
    const all = this.props.allTopicTasks.filter(all => all.topics.id === record.id)
    return <Task
      tasks={all[0].tasks}
      programId={id}
      isReadOnly={readOnly}
      topicId={record.id}
      operationEnable={this.state.operationEnable}
      selectedRowKeys={this.state.sourceTaskIds}
      selectTaskRows={((sourceTaskIds, selected) => this.selectTasks(sourceTaskIds, selected))}
    />
  }

  expandClose () {
    const {topicBoxPageState, allTopicTasks} = this.props
    const taskId = allTopicTasks.map(all => all.topics.id)

    if (topicBoxPageState.expandedRowKeys.length) {
      return <div className='all-expand-close cursor'>
        <Icon type='minus-square-o' onClick={() => this.onExpandedRowsChange([])} />
      </div>
    } else {
      return <div className='all-expand-close cursor'>
        <Icon type='plus-square-o' onClick={() => this.onExpandedRowsChange(taskId)} />
      </div>
    }
  }

  onExpandedRowsChange (expandedRowKeys) {
    const {topicBoxPageState} = this.props
    this.props.updateTopicBoxPageState({...topicBoxPageState, expandedRowKeys})
  }

  taskOperation (organizationId, topicId, operation) {
    const {sourceTaskIds} = this.state
    if (sourceTaskIds.length === 0) {
      message.warning(convertContent('未勾选任务卡'))
      return
    }
    operation === 'copy'
      ? this.props.copyToTopic(organizationId, sourceTaskIds, topicId, this.props.programId)
      : this.props.moveToTopic(sourceTaskIds, topicId, this.props.programId)

    this.setState({sourceTaskIds: []})
  }

  render () {
    const {expandedRowKeys} = this.props.topicBoxPageState
    const {program} = this.props
    const isReadOnly = program.readOnly

    const columns = [
      {
        title: convertContent('主题名称'),
        dataIndex: 'title',
        width: '60%',
        render: (text, record) => {
          return (
            <EditableCell
              isReadOnly={isReadOnly}
              value={text}
              id={record.id}
              onChange={this.onCellChange(record.id, 'title')}
            />)
        }
      },
      {
        title: convertContent('状态'),
        dataIndex: 'status',
        width: '10%',
        render: (text, record) => {
          return (
            <span>
              <ShowToStudentCell
                readOnly
                visibility={record.visible ? record.visible : 0}
                changeTopicVisible={this.props.changeTopicVisible}
                id={record.id}
                programId={record.programId}
              />
            </span>)
        }
      },
      {
        title: convertContent('操作'),
        dataIndex: 'operation',
        width: '30%',
        render: (text, record) => {
          return <div>
            {
              isReadOnly
                ? ''
                : <span>
                  <span>
                    <ShowToStudentCell
                      visibility={record.visible ? record.visible : 0}
                      changeTopicVisible={this.props.changeTopicVisible}
                      id={record.id}
                      programId={record.programId} />
                  </span>
                  <span className='ant-divider' />
                  <span>
                    {this.props.topics.length >= 1
                      ? (<Popconfirm
                        title={<div>
                          {convertContent('确定要删除吗?')}
                          <span className={record.title ? '' : 'hidden'}>
                            {convertContent('请输入要删除的主题名称')}
                            <Input onChange={this.getInputValue.bind(this)} />
                          </span>
                        </div>}
                        onConfirm={() => this.onDelete(record)}>
                        <a href=''>{convertContent('删除')}</a>
                      </Popconfirm>)
                      : null}
                  </span>
                  <span className='ant-divider' />
                  <span>
                    <a id='topic' className='drag-handle'>{convertContent('拖拽排序')}</a>
                  </span>
                </span>
            }

          </div>
        }
      }]

    const that = this
    const dragProps = {
      onDragEnd (fromIndex, toIndex) {
        const data = that.props.topics
        const item = data.splice(fromIndex, 1)[0]
        data.splice(toIndex, 0, item)
        that.props.dragSort(data, that.props.programId)
      },
      ignoreSelector: '.ant-table-expanded-row',
      nodeSelector: '.topic-row',
      handleSelector: '.drag-handle'
    }
    const {user, organizations} = this.props
    return (
      <div>
        <ReactDragListView {...dragProps}>
          {this.expandClose()}

          <Button type='primary' className='add-topic'
            disabled={isReadOnly}
            onClick={this.handleAdd.bind(this)}>{convertContent('新增主题')}</Button>
          <TaskOperation
            user={user}
            isReadOnly={isReadOnly}
            organizations={organizations}
            programId={this.props.programId}
            operationEnable={this.state.operationEnable}
            enableOperation={() => this.setState({operationEnable: true})}
            programsAndSubTopics={this.props.programsAndSubTopics}
            taskOperation={(organizationId, topicId, operation) => this.taskOperation(organizationId, topicId, operation)} />

          <Table dataSource={this.props.topics} columns={columns} pagination={false} bordered
            rowKey={record => record.id}
            expandedRowRender={this.expandedRowRender.bind(this)}
            expandedRowKeys={expandedRowKeys}
            rowClassName='topic-row'
            onExpandedRowsChange={this.onExpandedRowsChange.bind(this)}
          />
        </ReactDragListView>
      </div>
    )
  }
}

const mapStateToProps = ({programsAndSubTopics, topicBoxPageState, organizations, user, program}) => ({
  programsAndSubTopics,
  topicBoxPageState,
  organizations,
  user,
  program
})

const mapDispatchToProps = dispatch => ({
  deleteTopic: (programId, topicId) => dispatch(topicActions.deleteTopic(programId, topicId)),
  addTopic: (programId, newTopic) => dispatch(topicActions.addTopic(programId, newTopic)),
  updateTopic: (programId, topicId, value) => dispatch(topicActions.updateTopic(programId, topicId, value)),
  dragSort: (topics, programId) => dispatch(topicActions.dragSort(topics, programId)),
  changeTopicVisible: (visibility, id, programId) => dispatch(topicActions.changeTopicVisible(visibility, id, programId)),
  getProgramsAndSubTopics: () => dispatch(topicActions.getProgramsAndSubTopics()),
  copyToTopic: (organizationId, sourceTaskIds, topicId, programId) => dispatch(topicActions.copyToTopic(organizationId, sourceTaskIds, topicId, programId)),
  moveToTopic: (sourceTaskIds, topicId, programId) => dispatch(topicActions.moveToTopic(sourceTaskIds, topicId, programId)),
  updateTopicBoxPageState: state => dispatch({type: 'UPDATE_TOPIC_BOX_PAGE_STATE', state})
})

export default connect(mapStateToProps, mapDispatchToProps)(Topic)
